import { Breadcrumb, Button, Form, Input, Select, message, Radio, Divider, DatePicker, Table, Tag, Space, Popconfirm } from "antd";
import { HomeOutlined, ContainerOutlined, SearchOutlined, EditOutlined, DeleteOutlined } from "@ant-design/icons";
import { useEffect, useState } from "react";
import locale from 'antd/es/date-picker/locale/zh_CN'
import img404 from '@/assets/error.png'
import useChannel from '@/hooks/useChannel'
import http from '@/utils/http'
import { useNavigate } from "react-router-dom";
const Article = () => {
  const navigate = useNavigate()
  const { RangePicker } = DatePicker;
  const [articleForm] = Form.useForm();
  // 频道列表
  const { channelList } = useChannel()
  // 文章列表数据
  const [articleList, setArticleList] = useState({ list: [], count: 0 })
  // 入参数据
  const [params, setParams] = useState({
    page: 1, per_page: 5, begin_pubdate: null, end_pubdate: null, status: null, channel_id: null,
  })
  // 定义审核状态枚举
  const statusMap = {
    0: <Tag color="info">草稿</Tag>,
    1: <Tag color="primary">待审核</Tag>,
    2: <Tag color="success">审核通过</Tag>,
    3: <Tag color="warning">审核失败</Tag>,
  }

  // 搜索
  const onSearch = values => {
    console.log(values);
    const { status, channel_id, date } = values

    setParams(
      {
        ...params,
        status,
        channel_id,
        begin_pubdate: date && date[0].format("YYYY-MM-DD"),
        end_pubdate: date && date[1].format("YYYY-MM-DD"),
      }
    )

  };
  // 重置
  const onReset = values => {
    console.log(values);
    articleForm.resetFields();
    fetchArticleList()
  };

  // 页码改变
  const pageChange = (page) => {
    console.log(page);
    setParams({
      ...params,
      page
    })
  }
  // 删除文章
  const delArticle = (data) => {
    console.log('data:', data);
    
    http.delete(`/mp/articles/${data.id}`).then((res) => {
      message.success("删除成功")
      if(res.message === "OK") {
        fetchArticleList()
      }else {
        message.error(res.message || "删除失败")
      }
    })
  }

  // 获取文章列表
  const fetchArticleList = () => {
    http.get("/mp/articles", { params }).then((res) => {
      const { results, total_count } = res.data;
      console.log('results', res.data);

      setArticleList({
        list: results,
        count: total_count
      })
    })
  }

  useEffect(() => {
    fetchArticleList()
  }, [params])
  // 准备列数据
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      width: 120,
      render: cover => {
        return <img src={cover.images[0] || img404} width={80} height={60} alt="" />
      }
    },
    {
      title: '标题',
      dataIndex: 'title',
      width: 220
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: data => statusMap[data]
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate'
    },
    {
      title: '阅读数',
      dataIndex: 'read_count'
    },
    {
      title: '评论数',
      dataIndex: 'comment_count'
    },
    {
      title: '点赞数',
      dataIndex: 'like_count'
    },
    {
      title: '操作',
      render: data => {
        return (
          <Space size="middle">
            <Button type="primary" shape="circle" icon={<EditOutlined />} onClick={() => navigate(`/publish?id=${data.id}`)}/>
            <Popconfirm
              title="确认删除该条文章吗?"
              onConfirm={() => delArticle(data)}
              okText="确认"
              cancelText="取消"
            >
              <Button
                type="primary"
                danger
                shape="circle"
                icon={<DeleteOutlined />}
              />
            </Popconfirm>
          </Space>
        )
      }
    }
  ]
  return (
    <div className="Article">
      {/* 面包屑导航 */}
      <Breadcrumb
        items={[
          {
            title: (
              <>
                <HomeOutlined />
                <span>首页</span>
              </>
            ),
          },
          {
            title: (
              <>
                <ContainerOutlined />
                <span>文章列表</span>
              </>
            ),
          },
        ]}
      />
      <Divider />
      {/* 搜索项 */}
      <Form
        initialValues={{ status: '' }}
        autoComplete="off"
        layout="inline"
        onFinish={onSearch}
        form={articleForm}
      >
        <Form.Item label="状态" name="status">
          <Radio.Group>
            <Radio value={''}> 全部 </Radio>
            <Radio value={0}> 草稿 </Radio>
            <Radio value={1}> 待审核 </Radio>
            <Radio value={2}> 审核通过 </Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item
          label="频道"
          name="channel_id"
        >
          <Select
            showSearch
            placeholder="请选择频道"
            optionFilterProp="label"
            style={{ width: 180 }}
          >
            {channelList.map((item) => (
              <Select.Option key={item.id} value={item.id}>
                {item.name}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item label="日期" name="date">
          {/* 传入locale属性 控制中文显示*/}
          <RangePicker locale={locale}></RangePicker>
        </Form.Item>
        <Form.Item>
          <Space>
            <Button htmlType="button" onClick={onReset}>
              重置
            </Button>
            <Button type="primary" icon={<SearchOutlined />} htmlType="submit">
              查询
            </Button>
          </Space>
        </Form.Item>
      </Form>
      <Divider />
      {/* 表格 */}
      <Table rowKey="id" columns={columns} dataSource={articleList.list} pagination={{
        current: params.page,
        pageSize: params.per_page,
        onChange: pageChange,
        total: articleList.count,
        showTotal: (total) => `共 ${total} 条数据`,
      }} scroll={{ y: 550 }} />
    </div>
  )
};
export default Article;
